import os
import sys
import SCons.cpp
import rtconfig 

sconstruct = File('SConstruct')
fn = sconstruct.rfile()
name = fn.name
building_dir = os.path.dirname(fn.abspath)

if os.getenv('RTT_ROOT'):
    RTT_ROOT = os.getenv('RTT_ROOT')
else:
    RTT_ROOT = os.path.join(building_dir, '.', 'rt-thread')

RTT_RTGUI = os.getenv('RTT_RTGUI')
if not RTT_RTGUI:
    RTT_RTGUI = RTT_ROOT + '/components/rtgui/'

sys.path = sys.path + [os.path.join(RTT_ROOT, 'tools')]
from building import *

Export('RTT_ROOT')

# add target option
AddOption('--app',
  dest='app',
  nargs=1, type='string',
  action='store',
  metavar='DIR',
  help='installation prefix')

# add target option
AddOption('--type',
  dest='type',
  nargs=1, type='string',
  action='store',
  metavar='DIR',
  help='installation prefix')

if GetOption('type') == 'ext':
    linkflags = rtconfig.LFLAGS + ' -e 0'
else:
    linkflags = rtconfig.LFLAGS + ' -e main'

env = Environment(tools = ['mingw'],
        AS = rtconfig.AS, ASFLAGS = rtconfig.AFLAGS,
        CC = rtconfig.CC, CCFLAGS = rtconfig.CFLAGS,
        CXX = rtconfig.CXX, AR = rtconfig.AR, ARFLAGS = '-rc',
        LINK = rtconfig.LINK, LINKFLAGS = linkflags,
        LIBPATH = [os.path.join(building_dir, '..', 'libraries')],
        CPPPATH = [os.path.join(building_dir, '..', 'realtouch'), 
                RTT_ROOT + '/include',
                RTT_ROOT + '/components/finsh',
                RTT_ROOT + '/components/dfs', 
                RTT_ROOT + '/components/dfs/include',
                RTT_ROOT + '/components/libc/newlib',
                RTT_RTGUI + '/include'
                ])
env.PrependENVPath('PATH', rtconfig.EXEC_PATH)

PrepareModuleBuilding(env, RTT_ROOT)

app = GetOption('app')
if app:
    objs = SConscript(os.path.join(app, 'Sconscript'))
    TARGET = os.path.join('programs/' + app , app + '.' + rtconfig.TARGET_EXT)

    # build program 
    env.Program(TARGET, objs)
